//
//  Twitter03AppDelegate.m
//  iTweet
//
//  Created by Dang Duc Nam (namk42c@yahoo.com) on 5/12/09.
//  Copyright 2009 Unitech. All rights reserved.
//

#import <SystemConfiguration/SystemConfiguration.h>
#import "iTweetAppDelegate.h"
#import "TwitterListViewController.h"
#import "TwitterRepliesViewController.h"
#import "UserTimelineViewController.h"
#import "Status.h"
#import "User.h"
@implementation iTweetAppDelegate

@synthesize window;
@synthesize tabBarController;
@synthesize received_friend_timeline;
@synthesize received_images_small;
@synthesize received_images_large;
@synthesize received_user;
@synthesize received_replies;
@synthesize cached_users;

- (void)init {
	//NSLog(@"Application Init");
#define HOME_VIEW 0
#define REPLIES_VIEW 1
#define DIRECT_MESSAGES_VIEW 2
#define TWEET_VIEW 3
#define PROFILE_VIEW 4
#define MENU_VIEW 5
	
	NSString *nameValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"name_preference"];
	if (nameValue != nil) {
		NSString *password = [[NSUserDefaults standardUserDefaults] stringForKey:@"password_preference"];
		twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
		[twitterEngine setUsername:nameValue password:password];
		NSLog(@"User: %@, Password: %@", nameValue, password);
	}
	received_friend_timeline = [(NSMutableArray*)[NSMutableArray alloc] init];
	received_replies = [(NSMutableArray*)[NSMutableArray alloc] init];
	received_images_small = [(NSMutableDictionary*)[NSMutableDictionary alloc] init];
	received_images_large = [(NSMutableDictionary*)[NSMutableDictionary alloc] init];
	cached_users = [(NSMutableDictionary*)[NSMutableDictionary alloc] init];
	
	[super init];
}
-(void)setEngine:(NSString *)username password:(NSString *)password {
	_username = username;
	_password = password;
	twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
	[twitterEngine setUsername:_username password:_password];
	
}
-(void)goHome {
	[window addSubview:tabBarController.view];
	[self getStatus:0 count:20 refresh:NO];
}
- (BOOL)isDataSourceAvailable
{
    static BOOL checkNetwork = YES;
    if (checkNetwork) { // Since checking the reachability of a host can be expensive, cache the result and perform the reachability check once.
        checkNetwork = NO;
        Boolean success;
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        const char *host_name = "twitter.com";
		
        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name);
        SCNetworkReachabilityFlags flags;
        success = SCNetworkReachabilityGetFlags(reachability, &flags);
        _isDataSourceAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
        CFRelease(reachability);
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    }
    return _isDataSourceAvailable;
}
- (BOOL)isServiceAvailable {
	//network connection is ok, now we check for Twitter service is available
	static BOOL checkService = YES;
	if (checkService) {
		checkService = NO;
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		NSURL *url = [NSURL URLWithString:@"http://twitter.com/help/test.xml"];
		NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
		[theRequest setHTTPMethod:@"GET"];
		NSError *error;
		NSURLResponse * response;
		NSData *webData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];	
		NSString *serviceData = [[NSString alloc] initWithData:webData encoding:NSASCIIStringEncoding];
		if ([serviceData isEqualToString:@"<ok>true</ok>"]) {
			_isServiceAvailable = YES;
		} else {
			_isServiceAvailable = NO;
		}
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
		[serviceData release];
	}
	return _isServiceAvailable;
}
- (void)applicationDidFinishLaunching:(UIApplication *)application {
	//check if application preference is set
	UIViewController *viewHome = [tabBarController.viewControllers objectAtIndex:HOME_VIEW];
	viewHome.tabBarItem.title = NSLocalizedString(@"HomeKey", @"");
	[viewHome release];
	viewHome = [tabBarController.viewControllers objectAtIndex:REPLIES_VIEW];
	viewHome.tabBarItem.title = NSLocalizedString(@"RepliesKey", @"");
	[viewHome release];
	viewHome = [tabBarController.viewControllers objectAtIndex:DIRECT_MESSAGES_VIEW];
	viewHome.tabBarItem.title = NSLocalizedString(@"DirectMessagesKey", @"");
	[viewHome release];
	viewHome = [tabBarController.viewControllers objectAtIndex:TWEET_VIEW];
	viewHome.tabBarItem.title = NSLocalizedString(@"TweetViewKey", @"");
	[viewHome release];
	viewHome = [tabBarController.viewControllers objectAtIndex:PROFILE_VIEW];
	viewHome.tabBarItem.title = NSLocalizedString(@"ProfileViewKey", @"");
	[viewHome release];
	viewHome = [tabBarController.viewControllers objectAtIndex:MENU_VIEW];
	viewHome.tabBarItem.title = NSLocalizedString(@"MenuViewKey", @"");
	[viewHome release];
	
	//NSString *nameValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"name_preference"];
	if (twitterEngine == nil) {
		UIViewController *udvController = [[LoginViewController alloc] initWithNibName:@"LoginView" bundle:[NSBundle mainBundle]];
		[window addSubview:udvController.view];
	} else {
		// Add the tab bar controller's current view as a subview of the window
		[window addSubview:tabBarController.view];
	}
	[window setBackgroundColor:[UIColor blackColor]];
	[window makeKeyAndVisible];
}


/*
// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
	NSLog(@"View controller selected %@", viewController.title);
}
*/

/*
// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
}
*/

- (void)getStatus:(int)page count:(int)messages_count refresh:(Boolean)refresh_status {
	//ensure we getting only message for Home view
	current_user_timeline = nil;
	if (twitterEngine != nil) {
		if ([self isDataSourceAvailable] == YES && [self isServiceAvailable]==YES) {
			[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
			if (refresh_status==YES)
				[received_friend_timeline removeAllObjects];
			[twitterEngine getFollowedTimelineSinceID:0 startingAtPage:page count:messages_count];
		}
	}
}
- (void)getReplies:(int)page count:(int)messages_count refresh:(Boolean)refresh_status {
	//ensure we getting only message for Replies view
	current_user_timeline = nil;
	if (twitterEngine != nil) {
		if ([self isDataSourceAvailable] == YES && [self isServiceAvailable]==YES) {
			[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
			if (refresh_status==YES)
				[received_replies removeAllObjects];
			[twitterEngine getRepliesSinceID:0 startingAtPage:page count:messages_count];
		}
	}
}
- (void)getUserTimeline:(NSString *)username page:(int)page count:(int)messages_count refresh:(Boolean)refresh_status {
	if (twitterEngine != nil) {
		if ([self isDataSourceAvailable] == YES && [self isServiceAvailable]==YES) {
			[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
			User *u = (User*)[cached_users objectForKey:username];
			if (refresh_status==YES) {
				[u.statuses removeAllObjects];
				[cached_users setObject:u forKey:username];
			}
			if ([u.statuses count]==0) {
				current_user_timeline = username;
				[twitterEngine getUserTimelineFor:username sinceID:0 startingAtPage:page count:messages_count];
				[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			}
		}
	}
}
- (void)disableUpdatesFor:(NSString *)username {
	if (twitterEngine != nil) {
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		current_user_remove = [NSString stringWithString:username];
		[current_user_remove retain];
		[twitterEngine disableUpdatesFor:current_user_remove];
	}
}


-(UIImage *)getUserLargeImage:(User *)user {
	UIImage *img = (UIImage*)[received_images_large objectForKey:user.ident];
	if (img == nil) { //if image does not exist, so we fetch
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		NSString *profile_image_url = [user valueForKey:@"profile_image_url"];
		NSString *profile_image_url_large = [profile_image_url stringByReplacingOccurrencesOfString:@"_normal." withString:@"."];
		NSURL *url = [NSURL URLWithString:profile_image_url_large];
		img = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
		[received_images_large setObject:img forKey:user.ident];
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	} else { //if image already there, so we do nothing
		//NSLog(@"Ignore once");
	}
	return img;
}

-(User *)getUser:(NSString *)userID {
	User *user = (User*)[cached_users objectForKey:userID];
	if (user == nil) { //if user does not exist, so we fetch
		NSLog(@"NIL");

		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		current_user_info = [NSString stringWithString:userID];
		[current_user_info retain];
		[twitterEngine getUserInformationFor:current_user_info];
	} else { //if image already there, so we do nothing
		//NSLog(@"Ignore once");
	}
	return user;
}

-(UIImage *)getUserNormalImage:(User *)user {
	UIImage *img = (UIImage*)[received_images_small objectForKey:user.ident];
	if (img == nil) { //if image does not exist, so we fetch
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		NSString *profile_image_url = [user valueForKey:@"profile_image_url"];
		NSURL *url = [NSURL URLWithString:profile_image_url];
		img = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
		[received_images_small setObject:img forKey:user.ident];
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	} else { //if image already there, so we do nothing
		//NSLog(@"Ignore once");
	}
	return img;
}

- (void)dealloc {
    [tabBarController release];
    [window release];
    [super dealloc];
}

#pragma mark UIActionSheetDelegate methods
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 0) {
		//Go to login page
		UIViewController *udvController = [[LoginViewController alloc] initWithNibName:@"LoginView" bundle:[NSBundle mainBundle]];
		[window addSubview:udvController.view];
	} 
}

#pragma mark MGTwitterEngineDelegate methods


- (void)requestSucceeded:(NSString *)connectionIdentifier
{
    NSLog(@"Request succeeded for connectionIdentifier = %@", connectionIdentifier);
}


- (void)requestFailed:(NSString *)connectionIdentifier withError:(NSError *)error
{
    NSLog(@"Request failed for connectionIdentifier = %@, error = %@ (%@)", 
          connectionIdentifier, 
          [error localizedDescription], 
          [error userInfo]);
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	// TODO: check network again to validate that corrupted
	NSString *msgAlert;
	if (error.code == 401) {
		msgAlert = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"ErrorDescriptionKey",@""), NSLocalizedString(@"UnauthorizedKey",@"")];
	} else {
		msgAlert = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"ErrorDescriptionKey",@""), [error localizedDescription]];
	}
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:msgAlert delegate:self cancelButtonTitle:NSLocalizedString(@"CancelKey",@"") destructiveButtonTitle:NSLocalizedString(@"OKKey",@"") otherButtonTitles:nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
	[actionSheet showInView:tabBarController.view];
	[actionSheet release];
}


- (void)statusesReceived:(NSArray *)statuses forRequest:(NSString *)connectionIdentifier
{
	NSMutableArray *temp_status = [(NSMutableArray*)[NSMutableArray alloc] init];
	int i, count;
	count = [statuses count];
	for (i = 0; i < count; i++)
	{
		NSDictionary *status = [statuses objectAtIndex: i];
		Status *st = [(Status*)[Status alloc] init];
		st.created_at = [status valueForKey:@"created_at"];
		st.Ident = (NSNumber*)[status valueForKey:@"id"];
		st.text = [status valueForKey:@"text"];
		st.source = [status valueForKey:@"source"];
		st.truncated = (int)[status valueForKey:@"truncated"];
		st.favorited = (int)[status valueForKey:@"favorited"];
		st.in_reply_to_status_id = (NSNumber*)[status valueForKey:@"in_reply_to_status_id"];
		st.in_reply_to_status_id = (NSNumber*)[status valueForKey:@"in_reply_to_user_id"];
		//get user profile
		NSDictionary *user = [status valueForKey:@"user"];
		User *u = [(User*)[User alloc] init];
		u.created_at = [user valueForKey:@"created_at"];
		u.favourites_count = (NSNumber*)[user valueForKey:@"favourites_count"];
		u.followers_count = (NSNumber*)[user valueForKey:@"followers_count"];
		u.following = (int)[user valueForKey:@"following"];
		u.friends_count = (NSNumber*)[user valueForKey:@"friends_count"];
		u.ident = (NSNumber*)[user valueForKey:@"id"];
		u.name = [user valueForKey:@"name"];
		u.description = [user valueForKey:@"description"];
		u.location = [user valueForKey:@"location"];
		u.notifications = (int)[user valueForKey:@"notifications"];
		u.profile_background_color = [user valueForKey:@"profile_background_color"];
		u.profile_background_image_url = [user valueForKey:@"profile_background_image_url"];
		u.profile_background_tile = [user valueForKey:@"profile_background_tile"];
		u.profile_image_url = [user valueForKey:@"profile_image_url"];
		u.profile_link_color = [user valueForKey:@"profile_link_color"];
		u.profile_sidebar_border_color = [user valueForKey:@"profile_sidebar_border_color"];
		u.profile_sidebar_fill_color = [user valueForKey:@"profile_sidebar_fill_color"];
		u.profile_text_color = [user valueForKey:@"profile_text_color"];
		u.protected = (int)[user valueForKey:@"protected"];
		u.screen_name = [user valueForKey:@"screen_name"];
		u.statuses_count = (NSNumber*)[user valueForKey:@"statuses_count"];
		//add user to cache for later use
		[cached_users setObject:u forKey:[u.ident stringValue]];
		st.name = [user valueForKey:@"name"];
		st.screen_name = [user valueForKey:@"screen_name"];
		st.userID = u.ident;
		//get the image object from received_image_small
		UIImage *img = (UIImage*)[received_images_small objectForKey:st.userID];
		if (img == nil) { //if image does not exist, so we fetch
			NSString *profile_image_url = [user valueForKey:@"profile_image_url"];
			//profile_image_url = [profile_image_url stringByReplacingOccurrencesOfString:@"_" withString:@""];
			NSURL *url = [NSURL URLWithString:profile_image_url];
			// TODO: fix the nil image url
			NSError *er = [(NSError*)[NSError alloc] init];
			img = [UIImage imageWithData: [NSData dataWithContentsOfURL:url options:NSUncachedRead error:&er]];
			if (img==nil) {
				NSLog(@"Error code: %@",[er description]);
			}
			else {
				[received_images_small setObject:img forKey:st.userID];
			}
			[er release];
		} else { //if image already there, so we do nothing
			//NSLog(@"Ignore once");
		}
		//ensure that active view is a table view so it does have a top navigation view
		if ([[self.tabBarController selectedViewController] isKindOfClass:[UINavigationController class]]) {
			if ([[(UINavigationController *)[self.tabBarController selectedViewController] topViewController] isKindOfClass:[TwitterListViewController class]]) {
				[received_friend_timeline addObject:st];
				[[(TwitterListViewController *)[(UINavigationController *)[self.tabBarController selectedViewController] topViewController] tableView] reloadData];
			} else if ([[(UINavigationController *)[self.tabBarController selectedViewController] topViewController] isKindOfClass:[TwitterRepliesViewController class]]){
				[received_replies addObject:st];
				[[(TwitterRepliesViewController *)[(UINavigationController *)[self.tabBarController selectedViewController] topViewController] tableView] reloadData];
			} else if (current_user_timeline!=nil) {
				if (st!=nil)
					[temp_status addObject:st];
			}
		} 
	}
	if (current_user_timeline!=nil) {
		//[cached_user_statuses setObject:temp_status forKey:current_user_timeline];
		//cached_users.statuses = temp_status;
		User *user = [cached_users objectForKey:current_user_timeline];
		NSLog(@"User: %d", [cached_users count]);
		if (user!=nil) {
			user.statuses = [(NSMutableArray*)[NSMutableArray alloc] init];
			user.statuses = temp_status;
			[cached_users setObject:user forKey:current_user_timeline];
		}
		[[(UserTimelineViewController *)[(UINavigationController *)[self.tabBarController selectedViewController] topViewController] tableView] reloadData];		
		current_user_timeline = nil;
	}
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
-(void)reloadHome {
	//NSLog(@"Data Reloaded");
	[[(TwitterListViewController *)[self.tabBarController selectedViewController] tableView] reloadData];
}

- (void)directMessagesReceived:(NSArray *)messages forRequest:(NSString *)connectionIdentifier
{
    NSLog(@"Got direct messages for %@:\r%@", connectionIdentifier, messages);
}


- (void)userInfoReceived:(NSArray *)userInfo forRequest:(NSString *)connectionIdentifier
{
	//ensure that current user to remove set
	if (current_user_remove!=nil) {
		User *user = (User*)[cached_users objectForKey:current_user_remove];
		//[cached_users removeObjectForKey:current_user_remove];
		user.following = NO;
		[cached_users setObject:user forKey:current_user_remove];
		[current_user_remove release];
		current_user_remove = nil;
	}
	// if we are getting a user
	if (current_user_info!=nil) {
		NSLog(@"user info received");
		NSMutableDictionary *userDict = [userInfo objectAtIndex:0];
		NSLog(@"Got user\r: %@", userDict);
		[current_user_info release];
		current_user_info = nil;
	}
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}


- (void)miscInfoReceived:(NSArray *)miscInfo forRequest:(NSString *)connectionIdentifier
{
	NSLog(@"Got misc info for %@:\r%@", connectionIdentifier, miscInfo);
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (void)searchResultsReceived:(NSArray *)searchResults forRequest:(NSString *)connectionIdentifier
{
	NSLog(@"Got search results for %@:\r%@", connectionIdentifier, searchResults);
}

@end

